package com.controller;

import org.springframework.util.ObjectUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

/**
 * Authentication(验证），你的身份
 * Authorization（授权）：你能干什么
 */
public class AuthenticationInterceptor implements HandlerInterceptor {
   /* @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Object username = session.getAttribute("username");
        if (ObjectUtils.isEmpty(username)) {
            response.sendRedirect("/login");
            return false;
        }
        return true;
    }*/


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //第三个参数类型是HandlerMethod。里面有个成员method代表方法
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        boolean needAuth = method.isAnnotationPresent(Auth.class);

        if (needAuth) {
            HttpSession session = request.getSession();
            Object username = session.getAttribute("username");
            if (ObjectUtils.isEmpty(username)) {
                response.sendRedirect("/login");
                return false;
            }
            return true;
        } else {
            return true;
        }
    }
}
